package com.zhao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.Util.HttpContextUtil;
import com.zhao.Util.IPUtil;
import com.zhao.Util.MD5_Shiro;
import com.zhao.Util.VerifyCodeUtils;
import com.zhao.comm.log.MyLog;
import com.zhao.pojo.Filegroup;
import com.zhao.pojo.Groups;
import com.zhao.pojo.User;
import com.zhao.pojo.Wallet;
import com.zhao.service.FilegroupService;
import com.zhao.service.GroupsService;
import com.zhao.service.UserService;
import com.zhao.service.WalletService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Base64;
import java.util.Timer;
import java.util.TimerTask;

@Controller
@RequestMapping("/loginCenter")
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    WalletService walletService;
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    GroupsService groupsService;
    @Autowired
    FilegroupService filegroupService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    //@MyLog(value = "用户登录")  //日志
    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password, String ip, String ipHome) {
        System.out.println(password);
        byte[] decoded = Base64.getDecoder().decode(password);
        String pass = new String(decoded);
        System.out.println(pass);
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装使用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, pass);
        //执行登录的方法
        try {
            subject.login(token);
            User user = userService.getOne(new QueryWrapper<User>().eq("user_name", username));
            user.setIp(ip);
            user.setIpHome(ipHome);
            if (user.getIp().isEmpty()){
                HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
                user.setIp(IPUtil.getIpAddr(request));
            }
            if (user.getIpHome().isEmpty()){
                user.setIpHome("未知");
            }
            userService.updateById(user);
            return "1";
        } catch (UnknownAccountException e) {
           // model.addAttribute("msg","用户名错误");
            System.out.println("2");
            return "2";
        } catch (IncorrectCredentialsException e){
            //model.addAttribute("msg","密码错误");
            System.out.println("3");
            return "3";
        }
    }
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",null);
        subject.logout();
        return "login";
    }
    @RequestMapping("/noAuth")
    @ResponseBody
    public String noAuth(){
        return "未经授权，无法访问！";
    }
    //注册
    //@MyLog(value = "注册用户")  //日志
    @ResponseBody
    @RequestMapping("/register")
    public String register(String username,String password, String account,String email, String ip, String ipHome){
        byte[] decoded = Base64.getDecoder().decode(password);
        String pass = new String(decoded);
        User user = new User();
        user.setUserName(username);
        user.setUserPass(pass);
        user.setUserAccount(account);
        user.setUserEmail(email);
        user.setIp(ip);
        user.setIpHome(ipHome);
        if (user.getIp().isEmpty()){
            HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
            user.setIp(IPUtil.getIpAddr(request));
        }
        if (user.getIpHome().isEmpty()){
            user.setIpHome("未知");
        }
        String res = userService.addUser(user);
        User one = userService.getOne(new QueryWrapper<User>().eq("user_name", username));
        userService.registerUserRole(one.getUserId(),3);
        Wallet wallet = new Wallet();
        wallet.setAvatar("2021/8/moren.png");
        wallet.setUid(one.getUserId());
        walletService.save(wallet);
        //创建用户 默认分组
        Groups groups = new Groups();
        groups.setUid(one.getUserId());
        groups.setGname("默认分组");
        Filegroup filegroup = new Filegroup();
        filegroup.setUid(one.getUserId());
        filegroup.setFgname("默认分组");
        groupsService.save(groups);
        filegroupService.save(filegroup);

        return res;
    }
   // @MyLog(value = "修改密码")  //日志
    @ResponseBody
    @RequestMapping("/forget")
    public String forget(String username,String password){
        byte[] decoded = Base64.getDecoder().decode(password);
        String pass = new String(decoded);
        User user = userService.getOne(new QueryWrapper<User>().eq("user_name", username));
        String newPwd = MD5_Shiro.encryptPassword("MD5",pass,user.getSalt(),1024);
        user.setUserPass(newPwd);
        userService.updateById(user);
        return "1";
    }

    /**
     *
     * @param username
     * @param account
     * @param code
     * @param email
     * @param request
     * @return
     * @throws MessagingException
     */

    //校验 用户名 笔名 是否被注册 没有被注册 注册码
    @ResponseBody
    @RequestMapping("/check")
    public String check(String username, String account,String code,String email,HttpServletRequest request) {
        System.out.println(username+account);
        User ifUsername = userService.getOne(new QueryWrapper<User>().eq("user_name", username));
        User ifAccount = userService.getOne(new QueryWrapper<User>().eq("user_account", account));
        HttpSession session = request.getSession(true);
        String verifyCode = (String) session.getAttribute(email);
        if (ifUsername!=null){
            return "0";//用户名存在
        }else if (ifAccount!=null){
            return "-1";//笔名存在
        }else if (code == null && code.length() == 0){
            return "-2";//code 不能为空
        }else if (verifyCode == null && verifyCode.length() == 0){
            return "-3";//验证码过期
        }else if (!code.equals(verifyCode)){
            return "-4";//验证码有误
        }
        session.removeAttribute(email);//立即清除 也可以不开启
        return "1";
    }
    //校验 用户名 笔名 是否被注册 重置密码
    @ResponseBody
    @RequestMapping("/forgetCheck")
    public String forgetCheck(String username,String code,String email) {
        User ifUsername = userService.getOne(new QueryWrapper<User>().eq("user_name", username));
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        HttpSession session = request.getSession(true);
        String verifyCode = (String) session.getAttribute(email);
        if (ifUsername==null){
            return "-1";//用户名不存在
        }else if (code == null && code.length() == 0){
            return "-2";//code不能为空
        }else if (verifyCode == null && verifyCode.length() == 0){
            return "-3";//验证码已过期
        }else if (!code.equals(verifyCode)){
            return "-4";//验证码有误
        }
        session.removeAttribute(email);//立即清除 也可以不开启
        return "1";
    }
   // @MyLog(value = "发送验证码")  //日志
    @ResponseBody
    @RequestMapping("/send")
    public String send(String email,String title, HttpServletRequest request) throws MessagingException {
        HttpSession session = request.getSession(true);
        if (session.getAttribute(email)!=null){
            return "0";
        }
        // 生成随机字串 验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //可以注册的发送验证码到email
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setSubject(title);
        helper.setText("<body>验证码：<p style='color:red'>"+verifyCode.toLowerCase()+"</p></body>");
        helper.setTo(email);
        helper.setFrom("也许有用 技术论坛 - MAYBE IT WORKS"+'<'+"1433304356@qq.com"+'>');
        mailSender.send(mimeMessage);
        // 存入会话session
        session.setAttribute(email, verifyCode.toLowerCase());
        //定时5分钟删除验证码
        this.removeAttrbute(session, email);
        return "1";
    }
    /**
     * 设置3分钟后删除session中的验证码
     * @param session
     * @param attrName
     */
    private void removeAttrbute(final HttpSession session, final String attrName) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 删除session中存的验证码
                session.removeAttribute(attrName);
                timer.cancel();
            }
        }, 5 * 60 * 1000);
    }

}